package com.woniuxy.controller;

import com.woniuxy.common.CommonResult;
import com.woniuxy.entity.Manager;
import com.woniuxy.entity.ResponseEntity;
import com.woniuxy.service.ManagerService;
import com.woniuxy.util.JWTUtil;

import com.woniuxy.util.RedisUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.crypto.hash.SimpleHash;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * (Manager)表控制层
 *
 * @author makejava
 * @since 2021-05-15 17:38:51
 */
@RestController
@RequestMapping("manager")
public class ManagerController {

    /**
     * 服务对象
     */
    @Resource
    private ManagerService managerService;
//    @Resource
//    private RedisTemplate redisTemplate;


    /**
     * Auther: Hello Mr. Guo  <br/>
     * Date: 12:15:  <br/>
     * Description:redis工具类自动注入
     */
    @Resource
    private RedisUtils redisUtils;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Manager selectOne(Integer id) {
        return this.managerService.queryById(id);
    }


    @GetMapping("/login")
    public ResponseEntity login(@RequestParam("username") String username,
                                @RequestParam("password") String password) {


        redisUtils.set("username",username);

        //根据注册的时候 或者修改manager里面的加密方式来, 只要一样即可
        System.out.println(username+"!!!!!!!!!!!!!!!!!!"+password);
        SimpleHash md5 = new SimpleHash("MD5", password, username);
        String newPassword = md5.toHex();
        Manager manager = this.managerService.queryByUsername(username);
        if (manager.getPassword().equals(newPassword)) {

            return new ResponseEntity(200, "登录成功", JWTUtil.sign(username, newPassword));
        } else {
            throw new UnauthorizedException();
        }
    }

    /**
     * Auther: Hello Mr. Guo  <br/>
     * Date: 12:17:  <br/>
     * Description:在登陆界面显示用户名
     */
    @GetMapping("show")
    public Manager show(){
        String username = (String)redisUtils.get("username");
        Manager manager = this.managerService.queryByUsername(username);
        return manager;
    }

}
